package com.htudata.item.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import com.htudata.alarm.pojo.po.AlarmLevelPO;
import com.htudata.alarm.service.AlarmLevelService;
import com.htudata.common.service.TokenService;
import com.htudata.core.util.operation.*;
import com.htudata.history.service.HisService;
import com.htudata.item.dao.ItemDao;
import com.htudata.node.service.impl.NodeShowService;
import com.htudata.zabbix.history.service.HistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class ItemSelectServiceV2 {

  @Autowired
  private ItemKindService itemKindService;
  
  @Autowired
  private HistoryService historyService;
  
  @Autowired
  private HisService hisService;
  
  @Autowired
  private AlarmLevelService alarmLevelService;
  
  @Autowired
  private ItemDao itemDao;
  
  @Autowired
  private HttpServletRequest request;
  
  @Value("${show_default_value}")
  private String show_default_value;
  
  @Value("${item_value_decimal}")
  private int item_value_decimal;
  
  public static String getItemNameZH(String key, JSONObject itemInfosJSONObject) {
    if (!MapOperationUtils.isValidMap((Map)itemInfosJSONObject))
      return null; 
    if (itemInfosJSONObject.containsKey(key)) {
      String result = itemInfosJSONObject.getJSONObject(key).getString("name_zh");
      return result;
    } 
    return null;
  }
  
  public List<Map<String, Object>> getItems(String flowId, String nodeId, String a2) throws Exception {
    if (!NodeShowService.isValidFlowIdId(flowId) && !NodeShowService.isValidNodeId(nodeId))
      return Collections.EMPTY_LIST; 
    if (!NodeShowService.isValidFlowIdId(flowId) && NodeShowService.isValidNodeId(nodeId))
      return getItemsByNodeId(flowId, nodeId, a2); 
    if (NodeShowService.isValidFlowIdId(flowId) && !NodeShowService.isValidNodeId(nodeId))
      return getItemsByFlowId(flowId, nodeId, a2); 
    return Collections.EMPTY_LIST;
  }
  
  public List<Map<String, Object>> getItemsByNodeId(String flowId, String nodeId, String a2)throws Exception  {
    long userId = TokenService.getUserId(this.request);
    List<Long> userIds = null;
    long roleType = TokenService.getRoleType(this.request);
    if (roleType != -1L && roleType != 1L) {
      userIds = new ArrayList<>();
      userIds.add(Long.valueOf(userId));
    } 
    List<Map<String, Object>> result = new ArrayList<>();
    JSONArray showedItems = getShowItemsByNodeId(nodeId, userId);
    JSONObject showedItemsJSONObject = FastJsonOperationUtils.JSONArrayToJSONObejct(showedItems, "item_id", false);
    List<AlarmLevelPO> alarmLevelList = this.alarmLevelService.getAlarmLevelList(a2);
    JSONArray localItems = getItems("-1", nodeId, 0, userIds, userIds);
    JSONArray hisJSONArray = new JSONArray();
    JSONArray hisStrJSONArray = new JSONArray();
    if (CollectionsOperationUtils.isValidCollection((Collection)localItems)) {
      hisJSONArray = this.hisService.getHisByItemId((List)localItems, "his");
      hisStrJSONArray = this.hisService.getHisByItemId((List)localItems, "his_str");
    } 
    JSONObject hisJSONObject = FastJsonOperationUtils.JSONArrayToJSONObejct(hisJSONArray, "item_id", false);
    JSONObject hisStrJSONObject = FastJsonOperationUtils.JSONArrayToJSONObejct(hisStrJSONArray, "item_id", false);
    JSONArray items = new JSONArray();
    if (CollectionsOperationUtils.isValidCollection((Collection)localItems))
      items.addAll((Collection)localItems); 
    FastJsonOperationUtils.sortByIntField(items, "alarm_level", "desc");
    JSONObject itemInfosJSONObject = null;
    JSONObject itemAndNode = null;
    JSONObject history = null;
    int isShowed = 0;
    for (Object obj : items) {
      itemAndNode = (JSONObject)obj;
      if (hisJSONObject.containsKey(itemAndNode.getString("item_id"))) {
        history = (JSONObject)hisJSONObject.get(itemAndNode.getString("item_id"));
      } else if (hisStrJSONObject.containsKey(itemAndNode.getString("item_id"))) {
        history = (JSONObject)hisStrJSONObject.get(itemAndNode.getString("item_id"));
      } else {
        history = null;
      } 
      if (showedItemsJSONObject.containsKey(itemAndNode.getString("item_id"))) {
        isShowed = 1;
      } else {
        isShowed = 0;
      } 
      result.add(getItemWithHistory(itemAndNode, history, alarmLevelList, isShowed, itemInfosJSONObject));
    } 
    return result;
  }
  
  public List<Map<String, Object>> getItemsByFlowId(String flowId, String nodeId, String a2) throws Exception {
    long userId = TokenService.getUserId(this.request);
    List<Long> userIds = null;
    long roleType = TokenService.getRoleType(this.request);
    if (roleType != -1L && roleType != 1L) {
      userIds = new ArrayList<>();
      userIds.add(Long.valueOf(userId));
    } 
    List<Map<String, Object>> result = this.itemKindService.getItemKindListWithoutCache2(true);
    JSONArray showItems = getShowItemsByFlowId(flowId, userId);
    JSONObject showItemsJSONObject = FastJsonOperationUtils.JSONArrayToJSONObejct(showItems, "item_id", false);
    List<AlarmLevelPO> alarmLevelList = this.alarmLevelService.getAlarmLevelList(a2);
    JSONArray localItems = getItems(flowId, "-1", 0, userIds, userIds);
    JSONArray hisJSONArray = new JSONArray();
    JSONArray hisStrJSONArray = new JSONArray();
    if (CollectionsOperationUtils.isValidCollection((Collection)localItems)) {
      hisJSONArray = this.hisService.getHisByItemId((List)localItems, "his");
      hisStrJSONArray = this.hisService.getHisByItemId((List)localItems, "his_str");
    } 
    JSONObject hisJSONObject = FastJsonOperationUtils.JSONArrayToJSONObejct(hisJSONArray, "item_id", false);
    JSONObject hisStrJSONObject = FastJsonOperationUtils.JSONArrayToJSONObejct(hisStrJSONArray, "item_id", false);
    JSONArray items = new JSONArray();
    if (CollectionsOperationUtils.isValidCollection((Collection)localItems))
      items.addAll((Collection)localItems); 
    FastJsonOperationUtils.sortByIntField(items, "alarm_level", "desc");
    JSONObject itemInfosJSONObject = null;
    JSONObject itemAndNode = null;
    JSONObject history = null;
    Map<String, Object> firstKindMap = null;
    Map<String, Object> secondKindMap = null;
    List<Map<String, Object>> firstKindList = null;
    List<Map<String, Object>> secondKindList = null;
    List<Map<String, Object>> nodeList = null;
    Map<String, Object> node = null;
    List<Map<String, Object>> itemList = null;
    int isShowed = 0;
    for (Object obj : items) {
      itemAndNode = (JSONObject)obj;
      if (hisJSONObject.containsKey(itemAndNode.getString("item_id"))) {
        history = (JSONObject)hisJSONObject.get(itemAndNode.getString("item_id"));
      } else if (hisStrJSONObject.containsKey(itemAndNode.getString("item_id"))) {
        history = (JSONObject)hisStrJSONObject.get(itemAndNode.getString("item_id"));
      } else {
        history = null;
      } 
      if (showItemsJSONObject.containsKey(itemAndNode.getString("item_id"))) {
        isShowed = 1;
      } else {
        isShowed = 0;
      } 
      int firstKind = itemAndNode.getIntValue("first_Kind");
      int secondKind = itemAndNode.getIntValue("second_Kind");
      for (int i = 0, length = result.size(); i < length; ) {
        firstKindMap = result.get(i);
        if (!(firstKind + "").equals((new StringBuilder()).append(firstKindMap.get("type")).append("").toString())) {
          i++;
          continue;
        } 
        firstKindList = (List<Map<String, Object>>)firstKindMap.get("list");
        for (int j = 0, length2 = firstKindList.size(); j < length2; ) {
          secondKindMap = firstKindList.get(j);
          if (!(secondKind + "").equals((new StringBuilder()).append(secondKindMap.get("type")).append("").toString())) {
            j++;
            continue;
          } 
          secondKindList = (List<Map<String, Object>>)firstKindMap.get("list");
          nodeList = (List<Map<String, Object>>)((Map)secondKindList.get(j)).get("list");
          int count = 0;
          for (int k = 0, length3 = nodeList.size(); k < length3; ) {
            node = nodeList.get(k);
            if (!itemAndNode.getString("node_nick_name").equals((new StringBuilder()).append(node.get("name")).append("").toString())) {
              k++;
              continue;
            } 
            itemList = (List<Map<String, Object>>)node.get("list");
            itemList.add(getItemWithHistory(itemAndNode, history, alarmLevelList, isShowed, itemInfosJSONObject));
            firstKindMap.put("num", Integer.valueOf(Integer.parseInt((new StringBuilder()).append(firstKindMap.get("num")).append("").toString()) + 1));
            count++;
          } 
          if (count == 0) {
            itemList = new ArrayList<>();
            itemList.add(getItemWithHistory(itemAndNode, history, alarmLevelList, isShowed, itemInfosJSONObject));
            node = new HashMap<>();
            node.put("name", itemAndNode.getString("node_nick_name"));
            node.put("type", Integer.valueOf(itemAndNode.getIntValue("node_type_id")));
            node.put("stationTypeId", Integer.valueOf(itemAndNode.getIntValue("station_type_id")));
            node.put("state", Boolean.valueOf(true));
            node.put("list", itemList);
            nodeList.add(node);
            firstKindMap.put("num", Integer.valueOf(Integer.parseInt((new StringBuilder()).append(firstKindMap.get("num")).append("").toString()) + 1));
          } 
        } 
      } 
    } 
    return result;
  }
  
  public Map<String, Object> getItemWithHistory(JSONObject itemAndNode, JSONObject history, List<AlarmLevelPO> alarmLevelList, int isShowed, JSONObject itemInfosJSONObject)throws Exception  {
    Map<String, Object> result = new HashMap<>();
    result.put("state", Boolean.valueOf(true));
    result.put("itemId", itemAndNode.getString("item_id"));
    result.put("name", itemAndNode.getString("name"));
    AlarmLevelPO alarmLevelPO = AlarmLevelService.getAlarmLevelInfo(alarmLevelList, itemAndNode
        .getIntValue("alarm_level"));
    if (alarmLevelPO != null) {
      result.put("color", alarmLevelPO.getColor());
    } else {
      result.put("color", "#ffffff");
    } 
    if (isShowed != -1)
      if (0 == isShowed) {
        result.put("isShowed", Boolean.valueOf(false));
      } else if (1 == isShowed) {
        result.put("isShowed", Boolean.valueOf(true));
      }  
    String value = this.show_default_value;
    try {
      if (history != null)
        if ("0".equals(itemAndNode.getString("value_type"))) {
          value = MathOperationUtils.round(history.getOrDefault("value", "0") + "", this.item_value_decimal);
          value = StringOperationUtils.rvZeroAndDot(value);
          try {
            if ("B".equals(itemAndNode.getOrDefault("units", "") + "")) {
              Map<String, String> tranferedFileSize = FileOperationUtils.tranferFileSize2(Long.parseLong(value));
              value = tranferedFileSize.get("value");
              itemAndNode.put("units", tranferedFileSize.get("units"));
            } 
          } catch (Exception e) {
             throw e;
          } 
        } else {
          value = history.getString("value");
        }  
      if (StringOperationUtils.isValidStr2(value))
        if (itemAndNode.getOrDefault("key", "").equals("ping.host")) {
          if (Integer.parseInt(value) <= 0) {
            value = "无响应";
          } else if (Integer.parseInt(value) >= 100) {
            value = "正常";
          } else {
            value = "丢包";
          } 
        } else if ((itemAndNode.getOrDefault("key", "") + "").equals("agent.ping")) {
          if (Integer.parseInt(value) == 0) {
            value = "无响应";
          } else if (Integer.parseInt(value) == 1) {
            value = "正常";
          } else {
            value = this.show_default_value;
          } 
        } else if ((itemAndNode.getOrDefault("key", "") + "").contains("net.tcp.service")) {
          if (Integer.parseInt(value) == 0) {
            value = "无响应";
          } else if (Integer.parseInt(value) == 1) {
            value = "正常";
          } else {
            value = this.show_default_value;
          } 
        } else {
          value = value + itemAndNode.getOrDefault("units", "");
        }  
    } catch (Exception e) {
      throw e;
    } 
    result.put("value", value);
    return result;
  }
  
  @Deprecated
  public Map<String, List<String>> getItemIdMap(JSONArray itemAndNodes, JSONObject zbxItemsJSONObject) {
    Map<String, List<String>> result = new HashMap<>();
    List<String> itemIdList = null;
    JSONObject itemAndNode = null;
    JSONObject zbxItem = null;
    for (Object obj : itemAndNodes) {
      itemAndNode = (JSONObject)obj;
      if (!zbxItemsJSONObject.containsKey(itemAndNode.getString("item_id")))
        continue; 
      zbxItem = (JSONObject)zbxItemsJSONObject.get(itemAndNode.getString("item_id"));
      if (zbxItem.getIntValue("value_type") != 0)
        continue; 
      if (!result.containsKey(zbxItem.getString("value_type"))) {
        itemIdList = new ArrayList<>();
        itemIdList.add(itemAndNode.getString("item_id"));
        result.put(zbxItem.getString("value_type"), itemIdList);
        continue;
      } 
      ((List<String>)result.get(zbxItem.getString("value_type"))).add(itemAndNode.getString("item_id"));
    } 
    return result;
  }
  
  @Deprecated
  public JSONObject getHistory(Map<String, List<String>> itemIdMap, JSONArray itemAndNodes) throws Exception {
    JSONArray historyJSONArray = new JSONArray();
    JSONArray historyJSONArrayTemp = null;
    for (Map.Entry<String, List<String>> entry : itemIdMap.entrySet()) {
      historyJSONArrayTemp = this.historyService.getHistory(null, entry.getValue(), Integer.parseInt(entry.getKey()), -1, -1, ((List)entry
          .getValue()).size());
      if (!CollectionsOperationUtils.isValidCollection((Collection)historyJSONArrayTemp))
        continue; 
      historyJSONArray.addAll((Collection)historyJSONArrayTemp);
    } 
    if (!CollectionsOperationUtils.isValidCollection((Collection)historyJSONArray))
      return null; 
    JSONObject result = FastJsonOperationUtils.JSONArrayToJSONObejct(historyJSONArray, "itemid", false);
    return result;
  }
  
  public JSONArray getItemInfos() {
    return this.itemDao.selectItemInfos();
  }
  
  public JSONArray getNodeAndFlowByItemId(List<Object> idList) {
    return this.itemDao.selectNodesAndFlowsByItemId(idList);
  }
  
  public JSONArray getShowedItemsByFlowId(String flowId) {
    return this.itemDao.selectShowedItemsByFlowId(flowId);
  }
  
  public JSONArray getShowedLocalItemsByFlowId(String flowId, long userId, long getNodeOfUser) {
    return this.itemDao.selectShowedLocalItemsByFlowId(flowId, userId, getNodeOfUser);
  }
  
  public JSONArray getItems(String flowId, String nodeId, int isItemShowed, List<Long> userIds, List<Long> userIds2) {
    return this.itemDao.selectItems(flowId, nodeId, isItemShowed, userIds, userIds2);
  }
  
  public JSONArray getItemsAndNodes(String flowId, String nodeId, int isItemShowed) {
    return this.itemDao.selectItemsAndNodes(flowId, nodeId, isItemShowed);
  }
  
  public JSONArray getShowItemsByFlowId(String flowId, long userId) {
    return this.itemDao.selectShowItemsByFlowId(flowId, userId);
  }
  
  public JSONArray getShowItemsByNodeId(String flowId, long userId) {
    return this.itemDao.selectShowItemsByNodeId(flowId, userId);
  }
}
